﻿using System;
using System.Threading;
using System.Windows.Forms;
using ReportWizard.DataAccess;
using ReportWizard.Helpers;
using ReportWizard.Properties;
using Shortcut = ReportWizard.Helpers.Shortcut;

namespace ReportWizard.Forms
{
    public partial class LoginForm : IconForm
    {
        private bool FreeLoginGranted { get; set; }
        private string HostName { get; set; }

        private delegate void ParamsFreeVoidHandler();

        public LoginForm()
        {
            InitializeComponent();
            
            ShowCheckFooter = false;
            ShowCustomLeftButton = false;
            ShowCustomRightButton = false;
        }

        private int? Login()
        {
            string login = tbLogin.Text.Trim();
            string password = tbPassword.Text.Trim();

            if (!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(password))
            {
                int? userId = UserInfo.UserLogin(login, password);
                if (userId > 0)
                {
                    if (login.Equals(ConfigReader.DefaultUser) && password.Equals(ConfigReader.DefaultUser))
                    {
                        ShowMessage.Warning(string.Format("{0}\n{1}", Resources.MustChangePassword, Resources.MustChangePasswordPath));
                    }
                }
                else
                {
                    ShowMessage.Error(Resources.IncorrectLoginOrPassword);
                    return null;
                }
                return userId;
            }
            ShowMessage.Error(Resources.SetLoginAndPassword);
            return null;
        }

        private void Start()
        {
            HeaderImage = Resources.Emblems_emblem_unlocked_icon;
            LoginHost.RegisterLoginFromHost(Globals.CurrentUser.Id, HostName, checkRememberMe.Checked);

            new Thread(ShowMainForm).Start();
        }

        private void ShowMainForm()
        {
            Thread.Sleep(100);
            
            if (InvokeRequired)
            {
                ParamsFreeVoidHandler method = ShowMainForm;
                try
                {
                    Invoke(method);
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(ex);
                }
                return;
            }
            
            Hide();

            MainContainerForm mcf = new MainContainerForm();
            if (mcf.ShowDialog() == DialogResult.Cancel)
            {
                Application.Exit();
            }
        }

        private void ShowProgressForm1()
        {
            using (WaitProcess waitProcess = new WaitProcess(200))
            {
                for (int i = 0; i < 200; i++)
                {
                    Thread.Sleep(10);
                    Invoke(new MethodInvoker( waitProcess.DoStep));
                }
            }
        }

        private void ShowProgressForm()
        {
            Invoke(new MethodInvoker(ShowProgressForm1));
        }

        private void LoginForm_ClickCustomLeft(object sender, EventArgs e)
        {
            ShowProgressForm();
        }

        private void CheckSavedUser()
        {
            HostName = Globals.Host;

            UserInfo ui = LoginHost.GetAutoLoginForHost(HostName);
            if (ui != null)
            {
                checkRememberMe.Checked = true;

                Globals.CurrentUser = ui;
                tbLogin.Text = Globals.CurrentUser.Login;
                tbPassword.Text = new Random().Next(1000000000, int.MaxValue).ToString();

                FreeLoginGranted = true;
            }
        }

        private void LoginFormLoad(object sender, EventArgs e)
        {
            if (!UserInfo.IsDefaultUserExist())
            {
                UserInfo.CreateDefaultUser();
            }

            CheckSavedUser();
        }

        private void LoginInfoChanged(object sender, EventArgs e)
        {
            if (FreeLoginGranted)
            {
                FreeLoginGranted = false;
                checkRememberMe.Checked = false;
                Globals.CurrentUser = null;
            }
        }

        private void CheckPerferences()
        {
            if (!Perferences.CheckPerferences())
            {
                Shortcut.Create();
                Perferences.CreateDefaultPerferences();
            } 
        }

        private void LoginFormClickCancel(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void LoginFormClickOk(object sender, EventArgs e)
        {
            if (!FreeLoginGranted)
            {
                int? userId = Login();
                if (userId.HasValue && userId.Value > 0)
                {
                    Globals.CurrentUser = UserInfo.Select(userId.Value);
                    if (Globals.CurrentUser != null)
                    {
                        CheckPerferences();
                        Start();
                    }
                    else
                    {
                        ShowMessage.Error("Ошибка при получении данных пользователя.");
                    }
                }
            }
            else
            {
                CheckPerferences();
                Start();
            }
        }
    }
}